package com.hbfk.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.validation.annotation.Validated;

import lombok.Data;


public class BaseDao {
	private static BaseDao configManager;
	
	private static String dbType = "MySql";
	
	private static String dbMySqlDriver = "com.mysql.cj.jdbc.Driver";
	
	private static String mysqlUser="root";
	
	private static String mysqlPassword="123456";
	
	private static String mysqlUrl="jdbc:mysql://127.0.0.1:3306/jnpfdb?characterEncoding=utf8&useSSL=true&useOldAliasMetadataBehavior=true&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai";
	
	
	private static String dbOracleDriver = "oracle.jdbc.driver.OracleDriver";
	
	private static String oracleUser="HBGRCTEST";
	
	private static String oraclePassword="HBGRCTEST";
	
	private static String oracleUrl="jdbc:oracle:thin:@60.205.166.36:1521:orcl";
	
	
	static{
		try {
			if(dbType.equals("MySql")) {
				Class.forName(dbMySqlDriver);
			}else {
				Class.forName(dbOracleDriver);
			}
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
		}
	}

	
	
	private BaseDao(){
		
	}
	
	
	public static BaseDao getInstance() throws Exception{
		if(configManager==null){
			configManager = new BaseDao();
		}
		if(configManager == null) {
			//加入有一个线程走到这里,然后又然给另一个线程执行完
			synchronized(BaseDao.class) {
				if(configManager == null) {
					configManager = new BaseDao();
				}
			}
		}
		return configManager;
	}
	
	public Connection getConnection() throws SQLException {
		
		if(dbType.equals("MySql")) {
			return DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
		}else {
			return DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
		}
	}
	
	public void close(Connection con,ResultSet rs , Statement s){
		try {
			if(rs != null){
				rs.close();
			}
			if(s!=null){
				s.close();
			}
			if(con!=null){
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/** 判断数据库是否支持批处理 */
    public boolean supportBatch(Connection con) {
        try {
            // 得到数据库的元数据
            DatabaseMetaData md = con.getMetaData();
            return md.supportsBatchUpdates();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
